package com.down;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Random;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpProtocolParams;

public class FileDownloadUtil {
	
	static String urlStr = "/desk/bizhi/image/3/960x600/1373459291705.jpg";
	static String host = "b.zol-img.com.cn";
	static int port = 80;
	//socket
	static File file = new File("F:/downimg/123.png");
	public static void main1(String[] args) throws IOException {
		//String imgUrl = "/niona/pic/item/6db92dddabb31b225882ddcd.jpg";
		
		InetSocketAddress isa = new InetSocketAddress(host,
				port);
		SocketChannel client = SocketChannel.open();
		client.configureBlocking(false);
		Selector selector = Selector.open();
		client.register(selector, SelectionKey.OP_CONNECT);
		client.connect(isa);
		ByteBuffer buffer = ByteBuffer.allocate(2 * 1024);
        //int total = 0;
        for (;;) {
            selector.select();
            Iterator<SelectionKey> iter = selector.selectedKeys()
                .iterator();
            while (iter.hasNext()) {
              SelectionKey key = iter.next();
              iter.remove();
              if (key.isConnectable()) {
                SocketChannel channel = (SocketChannel) key
                    .channel();
                if (channel.isConnectionPending())
               
                //channel.write(buffer);
                channel.write(charset.encode("GET /desk/bizhi/image/3/960x600/1373459291705.jpg HTTP/1.1 "+ "\r\n\r\n"));
                System.out.println("channel.isConnectionPending()");
                channel.finishConnect();
                channel.register(selector, SelectionKey.OP_READ);
              } else if (key.isReadable()) {
                SocketChannel channel = (SocketChannel) key
                    .channel();
                int count = channel.read(buffer);
                if (count > 0) {
                  
                	fileOutput.write(buffer);
                	System.out.println(buffer);
                  buffer.clear();
                } else {
                  client.close();
                  break ;
                }
              }
            }
          }
	}

	//nio
	public static void main2(String[] args) {
		 SocketChannel channel = null;
		 InetSocketAddress socketAddress = null;
		 FileChannel fcout = null;
		 FileOutputStream fout = null;
		try {
            socketAddress = new InetSocketAddress(imgHost, 80);
            //step1:打开连接
            channel = SocketChannel.open(socketAddress);
 
            //step2:发送请求，使用XXX编码
            channel.write(charset.encode("GET "+imgPath+" HTTP/1.1" + "\r\nHost: "+imgHost+"\r\n\r\n"));
 
            fout = new FileOutputStream(outfile);// 获取目标文件的输出流;
            fcout = fout.getChannel(); // 获取输出通道;
 
            //step3:读取数据
            ByteBuffer buffer = ByteBuffer.allocate(1024);// 创建1024字节的缓冲
            boolean issub = false;
			while (channel.read(buffer) != -1) {
				buffer.flip(); // flip方法让缓冲区可以将新读入的数据写入另一个通道(切换读写);
				byte[] cont = buffer.array();
				if (!issub) {
					String htmlCont = new String(cont, charset);
					if (htmlCont.contains("\r\n\r\n")) {
						issub=true;
						htmlCont = htmlCont.substring(
								htmlCont.indexOf("\r\n\r\n") + 4,
								htmlCont.length());
					}
					byte[] buts = htmlCont.getBytes();
					fcout.write(ByteBuffer.allocate(buts.length).get(buts));
				}else{
					fcout.write(buffer);
				}
				// System.out.println(charset.decode(buffer));//
				// 使用Charset.decode方法将字节转换为字符串;
				
				buffer.clear();// 清空缓冲;
			}
        } catch (IOException e) {
           e.printStackTrace();
        } finally {
            close(channel, fcout, fout);
        }
	}

	private static void close(SocketChannel channel, FileChannel fcout,
			FileOutputStream fout) {
		if (channel != null) {
		    try {
		        channel.close();
		    } catch (IOException e) {
		    }
		}
		if (fcout != null) {
		    try {
		    	fcout.close();
		    } catch (IOException e) {
		    }
		}
		if (fout != null) {
		    try {
		    	fout.close();
		    } catch (IOException e) {
		    }
		}
	}
	
	private static Charset charset = Charset.forName("UTF-8");// 创建XXX(UTF-8)字符集
	static String imgHost = "http://img3.cache.netease.com";
	static String imgPath = "/photo/0001/2016-09-06/C09QRBE06VVV0001.jpg";
	static String outfile = "F:\\downimg\\name.jpg"; //输出到桌面的相关文件中;
	static FileChannel fcout = null;
	static FileOutputStream fout = null;
	public static void main(final String[] args) throws Exception {
		 outfile = outfile.replace("name", new Random().nextInt(1000)+"");
		 fout = new FileOutputStream(outfile);// 获取目标文件的输出流;
		HttpClientBuilder httpclientBuilder = HttpClientBuilder.create();
		CloseableHttpClient httpClient = httpclientBuilder.build();
		
        HttpGet httpGet = new HttpGet(imgHost+imgPath);
        //HttpProtocolParams pp = new HttpProtocolParams();
        CloseableHttpResponse httpresponse =httpClient.execute(httpGet);
        if(httpresponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
        	HttpEntity emtity = httpresponse.getEntity();
        	Long entityLength = emtity.getContentLength();
        	InputStream inputstream = httpresponse.getEntity().getContent();
        	int i = 0,c=1,size=512;
        	byte[] contentbytearray = new byte[size];
        	while((i=inputstream.read(contentbytearray))!=-1){
        		fout.write(contentbytearray,0,i);
        	}
        }
        close(null, fcout, fout);
	}
	static FileChannel fileOutput = null;
	static {
		try {
			if (!file.exists()) {
				file.createNewFile();
			}
			fileOutput = new FileOutputStream(file).getChannel();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
